<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;

use App\Http\Requests;

use Intervention\Image\ImageManagerStatic as Image;

use App\Http\Controllers\Controller;

use DB;
class infoController extends Controller
{
    //个人信息页面
    public function index()
    {
        // 查找用户信息表且名字为当前登录的用户名
        $list = DB::table('storeuser')
            ->where('userName','=',session('user')->userName)
            ->get();
        return view('home.info',['list'=>$list]);
    }

    public function edit($id)
    {
        $value = DB::table('storeuser')->where('userId',$id)->first();
        return view('home.info',['v'=>$value]);
    }

    public function update($id,Request $request)
    {
        // 自定义错误信息
        $message = [
            'required' => ':attribute 字段值是必填项',
            'digits' => ':attribute 字段值必须为数值且长度为11',
        ];
        //设定验证规则
        $this->validate($request, [
            'userTel' => 'required|digits:11',
            'userEmail' => 'required',
            'userImg' => 'required',
        ],$message);

        // 上传头像
        if($request->hasFile('userImg')){
                $file = $request->file('userImg');
                if ($file->isValid()) {
                    //获取后缀
                    $ext = $file->getClientOriginalExtension();
                    $picname = time().rand(1000,9999).'.'.$ext;
                    $file->move('./uploads/',$picname);
                    if($file->getError()>0){
                        echo '上传失败';
                    }else{
                        echo '上传成功';
                    } 
                }
            }

        // 去除不需要的字段 
        $data = $request->except('_token','_method');
        $data['userImg'] = './uploads/'.$picname;
        $row = DB::table('storeuser')->where('userId',$id)->update($data);
        if($row>0){
            return redirect('/info')->with('msg','修改成功');
        }
    }
}
